package OrderService

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/OrderReq"
	"gdshop-font-api-go/app/response/AddressResp"
	"gdshop-font-api-go/app/response/MemberResp"
	"gdshop-font-api-go/app/response/OrderResp"
	"gdshop-font-api-go/app/service/AddressService"
	"gdshop-font-api-go/app/service/CartServiceBase"
	"gdshop-font-api-go/app/service/FenxiaoService"
	"gdshop-font-api-go/app/service/GoodsBaseService"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	"gdshop-font-api-go/library/tools/OrderQueue"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

func Submit(ctx context.Context, parames *OrderReq.SubmitGroup) *response.JsonResponse {
	if parames.AddressId < 1 {
		return response.FailByRequestMessage(nil, "请选择收货地址")
	}
	messageId, err := DoSubmitOrderByQueue(ctx, parames)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功",
		g.Map{
			"message_id": messageId,
		})
}
func SubmitQueue(ctx context.Context, data *OrderReq.SubmitQueue) *response.JsonResponse {
	var parames *OrderReq.Submit
	doVar, err := g.Redis().DoVar("GET", "SubmitQueue:"+data.MessageId)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if doVar.IsEmpty() {
		return response.FailByRequestMessage(nil, "下单失败")
	}
	err = doVar.Struct(&parames)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if parames.AddressId < 1 {
		return response.FailByRequestMessage(nil, "请选择收货地址")
	}
	orderId, err := DoSubmitOrder(ctx, parames)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功",
		g.Map{
			"order_id": orderId,
		})
}
func SubmitEventBus(ctx context.Context, parames *OrderReq.Submit) *response.JsonResponse {
	if parames.AddressId < 1 {
		return response.FailByRequestMessage(nil, "请选择收货地址")
	}
	orderId, err := DoSubmitOrder(ctx, parames)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功",
		g.Map{
			"order_id": orderId,
		})
}
func DoSubmitOrderByQueue(ctx context.Context, parames *OrderReq.SubmitGroup) (string, error) {
	/*var mcList []*MemberResp.MemberCoupon
	var err error
	if parames.CouponIds != nil || len(parames.CouponIds) > 0 {
		// 如果第一个上送为 0 说明不使用优惠券
		if parames.CouponIds[0] != 0 {
			// 先检测提交上来的优惠券
			mcList, err = getMemberCouponListByMemberId(ctx, int(parames.MemberId), parames.CouponIds)
			if err != nil {
				return "", err
			}
			if mcList == nil {
				return "", errors.New("找不到优惠券")
			}
			if len(mcList) != len(parames.CouponIds) {
				return "", errors.New("我的优惠券和选中的优惠券不一致")
			}
		}
	}
	// 先做预下单检测
	_, err = CheckStore(ctx, &parames.SubmitItem, mcList)
	if err != nil {
		g.Log().Error("doSubmitInfo => checkStore 错误：" + err.Error())
		return "", err
	}
	// 预下单检测通过，开始检测收货地址
	addressModel := AddressService.GetMemberModel(ctx, parames.AddressId, int(parames.MemberId))
	if addressModel == nil {
		return "", errors.New("找不到收货地址")
	}*/
	// 写入数据库
	messageId, err := OrderQueue.AddSubmitOrder(*parames)
	if err != nil {
		return "", err
	}

	return messageId, nil
}

// 获取会员 已选择并且可用的优惠券
func getMemberCouponListByMemberId(ctx context.Context, memberId int, couponIds []int) ([]*MemberResp.MemberCoupon, error) {
	var mcList []*MemberResp.MemberCoupon
	err := toolsDb.GetUnSafaTable(ctx, "member_coupon").As("mc").LeftJoin("gd_coupon c", "mc.coupon_id = c.id AND c.delete_at < 1").Where(
		"mc.delete_at < 1 AND mc.member_id = ? AND mc.id IN (?) AND mc.use_time < 1 AND (mc.expires_time=0 OR mc.expires_time >= ?)",
		memberId, couponIds, time.Now().Unix()).Fields(
		"c.*,mc.id AS mc_id").Structs(&mcList)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errors.New("找不到会员优惠券")
		}
		return nil, err
	}
	return mcList, nil
}

// 按分组下单
func DoSubmitOrderGroup(ctx context.Context, parames *OrderReq.SubmitGroup) *response.JsonResponse {
	if parames.CartData != nil {
		// 预下单检测通过，开始检测收货地址
		addressModel := AddressService.GetMyAddressModel(ctx, parames.AddressId, int(parames.MemberId))
		if addressModel == nil {
			return response.FailByRequestMessage(nil, "找不到收货地址")
		}
		parames.Create.MemberId = parames.MemberId
		orderGroups, err := doCreateCartData(ctx, parames.Create)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		orderIds := []int{}
		// 循环写入订单
		for _, order := range orderGroups.OrderList {
			one, err := DoSubmitOrderOne(ctx, int(parames.MemberId), addressModel, order)
			if err != nil {
				return response.FailByRequestMessage(nil, err.Error())
			}
			fmt.Println("下单成功 ", one)
			orderIds = append(orderIds, one)
		}

		return response.SuccessByRequestMessageData(nil, "成功",
			g.Map{
				"order_ids": orderIds,
			})

	}
	if parames.OneData != nil {
		// 预下单检测通过，开始检测收货地址
		addressModel := AddressService.GetMyAddressModel(ctx, parames.AddressId, int(parames.MemberId))
		if addressModel == nil {
			return response.FailByRequestMessage(nil, "找不到收货地址")
		}
		parames.Create.MemberId = parames.MemberId
		orderGroups, err := doCreateOneData(ctx, parames.Create)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}

		orderIds := []int{}
		// 循环写入订单
		for _, order := range orderGroups.OrderList {
			// 单个下单的，循环 goods 里面的 活动ID出来，赋值给 groupID
			order.GroupId = order.Goodss[0].ActivityId
			one, err := DoSubmitOrderOne(ctx, int(parames.MemberId), addressModel, order)
			if err != nil {
				return response.FailByRequestMessage(nil, err.Error())
			}
			fmt.Println("下单成功 ", one)
			orderIds = append(orderIds, one)
		}

		return response.SuccessByRequestMessageData(nil, "成功",
			g.Map{
				"order_ids": orderIds,
			})

	}

	return response.FailByRequestMessage(nil, "不支持当前模式")
}

// 按单个下单
func DoSubmitOrderOne(ctx context.Context, memberId int, addressModel *AddressResp.Item,
	oneOrderData *OrderResp.OrderItem) (int, error) {
	// 写入数据库
	// 生成订单号
	orderNo, idErr := tools.GetOrderNo(1)
	if idErr != nil {
		return 0, idErr
	}
	goodsKey := []string{}
	for _, item := range oneOrderData.Goodss {
		goodsKey = append(goodsKey, item.GoodsName)
	}
	memberCouponIds := []int{}
	if oneOrderData.McId > 0 {
		memberCouponIds = append(memberCouponIds, oneOrderData.McId)
	}
	var err error
	/*g.Dump(oneOrderData.Goodss)
	g.Dump(aModel.Goodss)
	return 0, errors.New("测试")*/
	//g.Dump(oneOrderData)
	//return 0, errors.New("测试")
	var orderId int64
	var tmpGoods *OrderReq.OrderSubItem
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		// 写主表数据
		orderData := g.Map{}
		orderData["order_no"] = orderNo
		orderData["member_id"] = memberId
		orderData["store_id"] = oneOrderData.StoreId
		orderData["address_id"] = addressModel.Id
		orderData["total_price"] = int64(oneOrderData.TotalPrice) - oneOrderData.DiscountMoney - oneOrderData.ActivityDiscountMoney
		orderData["original_total_price"] = oneOrderData.TotalPrice
		orderData["dispatch_price"] = oneOrderData.Freight
		orderData["original_dispatch_price"] = oneOrderData.Freight
		orderData["create_at"] = time.Now().Unix()
		orderData["recipient_name"] = addressModel.Addressee
		orderData["recipient_mobile"] = addressModel.Mobile
		orderData["goods_key"] = strings.Join(goodsKey, "-")

		orderR, orderErr := tx.Model("order").Unscoped().Insert(orderData)
		if orderErr != nil {
			return orderErr
		}
		orderId, err = orderR.LastInsertId()
		if err != nil {
			return err
		}
		// 写 order_address 数据
		_, oae := tx.Model("order_address").Unscoped().Insert(g.Map{
			"order_id":     orderId,
			"address_json": addressModel,
		})
		if oae != nil {
			return oae
		}
		reduceGoodsStocks := []*OrderReq.ReduceGoodsStockUpdate{}
		for _, goods := range oneOrderData.Goodss {
			// 写 order_sub 数据
			tmpGoods = &OrderReq.OrderSubItem{
				Details:    goods.Details,
				Total:      goods.BuyNum,
				TotalPrice: goods.Options[0].SellPrice * int64(goods.BuyNum),
				OptionId:   int(goods.Options[0].Id),
			}
			osId, err := handleOrderSub(ctx, tx, orderId, memberId, tmpGoods, goods.Paid, tmpGoods.TotalPrice-goods.Paid)
			if err != nil {
				return err
			}
			// 先 处理 活动
			if oneOrderData.GroupId > 0 {
				err = handleOrderSubActivityByCreate(tx, orderId, osId, tmpGoods, oneOrderData)
				if err != nil {
					return err
				}
			}
			// 再 处理 order_sub_coupon 相关，通过活动优惠价和最后实付价格对比差额
			if oneOrderData.McId > 0 {
				err = handleOrderSubCouponsByCreate(tx, orderId, osId, tmpGoods, oneOrderData)
				if err != nil {
					return err
				}
			}
			// 写 order_sub_snapshot 数据
			_, osse := tx.Model("order_sub_snapshot").Unscoped().Insert(g.Map{
				"order_sub_id": osId,
				"goods_json":   goods,
			})
			if osse != nil {
				return osse
			}
			// 扣库存
			reduceGoodsStocks = append(reduceGoodsStocks, &OrderReq.ReduceGoodsStockUpdate{
				OrderSubId:     osId,
				GoodsId:        int(goods.Id),
				GoodsOptionId:  int64(goods.Options[0].Id),
				ReduceStockNum: int64(goods.BuyNum),
			})
		}
		// 扣优惠券
		err = memberUseCouponByMemberCouponIds(tx, memberCouponIds)
		if err != nil {
			return err
		}
		// 扣库存 加销量
		err = reduceGoodsStock(tx, reduceGoodsStocks)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return 0, err
	}

	return int(orderId), nil
}

// 老版下单
func DoSubmitOrder(ctx context.Context, parames *OrderReq.Submit) (int, error) {
	var mcList []*MemberResp.MemberCoupon
	var err error
	if parames.CouponIds != nil || len(parames.CouponIds) > 0 {
		// 先检测提交上来的优惠券
		if parames.CouponIds[0] != 0 {
			mcList, err = getMemberCouponListByMemberId(ctx, int(parames.MemberId), parames.CouponIds)
			if err != nil {
				return 0, err
			}
			if mcList == nil {
				return 0, errors.New("找不到优惠券")
			}
			if len(mcList) != len(parames.CouponIds) {
				return 0, errors.New("我的优惠券和选中的优惠券不一致")
			}
		}
	}
	// 先做预下单检测
	checkResults, err := CheckStore(ctx, &parames.SubmitItem, mcList)
	if err != nil {
		g.Log().Error("doSubmitInfo => checkStore 错误：" + err.Error())
		return 0, err
	}
	// 预下单检测通过，开始检测收货地址
	addressModel := AddressService.GetMyAddressModel(ctx, parames.AddressId, int(parames.MemberId))
	if addressModel == nil {
		return 0, errors.New("找不到收货地址")
	}
	// 写入数据库
	// 生成订单号
	orderNo, idErr := tools.GetOrderNo(1)
	if idErr != nil {
		return 0, idErr
	}

	memberCouponIds := []int{}
	if mcList != nil {
		for _, item := range mcList {
			memberCouponIds = append(memberCouponIds, item.MemberCouponId)
		}
	}

	var orderId int64
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		// 写主表数据
		orderData := g.Map{}
		orderData["order_no"] = orderNo
		orderData["member_id"] = parames.MemberId
		orderData["store_id"] = parames.StoreId
		orderData["address_id"] = parames.AddressId
		orderData["total_price"] = checkResults.TotalPrice
		orderData["original_total_price"] = checkResults.OriginalTotalPrice
		orderData["dispatch_price"] = checkResults.Freight
		orderData["original_dispatch_price"] = checkResults.Freight
		orderData["create_at"] = time.Now().Unix()
		orderData["recipient_name"] = addressModel.Addressee
		orderData["recipient_mobile"] = addressModel.Mobile
		orderData["goods_key"] = checkResults.GoodsKey

		orderR, orderErr := tx.Model("order").Unscoped().Insert(orderData)
		if orderErr != nil {
			return orderErr
		}
		orderId, err = orderR.LastInsertId()
		if err != nil {
			return err
		}
		// 写 order_address 数据
		_, oae := tx.Model("order_address").Unscoped().Insert(g.Map{
			"order_id":     orderId,
			"address_json": addressModel,
		})
		if oae != nil {
			return oae
		}
		reduceGoodsStocks := []*OrderReq.ReduceGoodsStockUpdate{}
		for _, goods := range checkResults.GoodsList {
			// 写 order_sub 数据
			osId, err := handleOrderSub(ctx, tx, orderId, int(parames.MemberId), goods,
				getOrderSubPaidOrDiscount("paid",
					goods, checkResults.UseCouponOrderSubs),
				getOrderSubPaidOrDiscount("discount",
					goods, checkResults.UseCouponOrderSubs))
			if err != nil {
				return err
			}
			// 处理 order_sub_coupon 相关
			err = handleOrderSubCoupons(tx, orderId, osId, goods, checkResults.UseCouponOrderSubs)
			if err != nil {
				return err
			}
			// 写 order_sub_snapshot 数据
			_, osse := tx.Model("order_sub_snapshot").Unscoped().Insert(g.Map{
				"order_sub_id": osId,
				"goods_json":   goods,
			})
			if osse != nil {
				return osse
			}
			// 扣库存
			reduceGoodsStocks = append(reduceGoodsStocks, &OrderReq.ReduceGoodsStockUpdate{
				OrderSubId:     osId,
				GoodsId:        int(goods.Id),
				GoodsOptionId:  int64(goods.Options[0].Id),
				ReduceStockNum: int64(goods.Total),
			})
		}
		// 扣优惠券
		err = memberUseCouponByMemberCouponIds(tx, memberCouponIds)
		if err != nil {
			return err
		}
		// 扣库存 加销量
		err = reduceGoodsStock(tx, reduceGoodsStocks)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return 0, err
	}
	// 下单成功，删除购物车
	_, delsErr := CartServiceBase.Dels(ctx, parames.CartIds, parames.MemberId)
	if delsErr != nil {
		g.Log().Async().Errorf("清除购物车失败 msg:%s ; CartIds:%s ; MemberId:%s",
			delsErr.Error(),
			parames.CartIds, parames.MemberId)
	}

	// 添加订单超时关闭队列
	go AddCloseNoPayOrder(int(orderId))

	return int(orderId), nil
}

// 处理 order_sub 数据
func handleOrderSub(ctx context.Context, tx *gdb.TX, orderId int64, memberId int, goods *OrderReq.OrderSubItem,
	paid, discount int64) (int64, error) {
	subOrderNO, err := tools.GetOrderNo(2)
	if err != nil {
		return 0, err
	}
	osData := entity.OrderSub{
		OrderId:          orderId,
		OrderSubNo:       subOrderNO,
		GoodsId:          int(goods.Id),
		StoreId:          goods.StoreId,
		GoodsName:        goods.GoodsName,
		SubTitle:         goods.SubTitle,
		GoodsCover:       goods.Cover,
		GoodsThumbs:      strings.Join(GoodsBaseService.GetGoodsThumbsByGoodsId(ctx, gconv.String(goods.Id), ""), ","),
		GoodsCates:       goods.Cates,
		MarketPrice:      goods.Options[0].MarketPrice,
		SellPrice:        goods.Options[0].SellPrice,
		CostPrice:        goods.Options[0].CostPrice,
		Total:            goods.Total,
		Paid:             paid,     // 子订单应付 （减去优惠后的） 单位分
		Discount:         discount, // 优惠金额 单位分
		GoodsSpu:         goods.Spu,
		GoodsOptionId:    int(goods.Options[0].Id),
		GoodsOptionTitle: goods.Options[0].Title,
		GoodsOptionThumb: goods.Options[0].Thumb,
		GoodsOptionSpecs: goods.Options[0].Specs,
		GoodsOptionSku:   goods.Options[0].GoodsSn,
	}
	osId, ose := tx.Model("order_sub").Unscoped().InsertAndGetId(osData)
	/*osId, ose := tx.Model("order_sub").Unscoped().InsertAndGetId(g.Map{
		"order_id":           orderId,
		"order_sub_no":       subOrderNO,
		"goods_id":           goods.Id,
		"store_id":           goods.StoreId,
		"goods_name":         goods.GoodsName,
		"sub_title":          goods.SubTitle,
		"goods_cover":        goods.Cover,
		"goods_thumbs":       strings.Join(GoodsService.GetGoodsThumbsByGoodsId(ctx, gconv.String(goods.Id), ""), ","),
		"goods_cates":        goods.Cates,
		"market_price":       goods.Options[0].MarketPrice,
		"sell_price":         goods.Options[0].SellPrice,
		"cost_price":         goods.Options[0].CostPrice,
		"total":              goods.Total,
		"paid":               paid,     // 子订单应付 （减去优惠后的） 单位分
		"discount":           discount, // 优惠金额 单位分
		"goods_spu":          goods.Spu,
		"goods_option_id":    goods.Options[0].Id,
		"goods_option_title": goods.Options[0].Title,
		"goods_option_thumb": goods.Options[0].Thumb,
		"goods_option_specs": goods.Options[0].Specs,
		"goods_option_sku":   goods.Options[0].GoodsSn,
	})*/

	if ose != nil {
		return 0, ose
	}

	// 处理 分销
	osData.Id = int(osId)
	FenxiaoService.AddFenxiaoOrder(tx, memberId, osData)

	return osId, nil
}

// 处理 活动
func handleOrderSubActivityByCreate(tx *gdb.TX, orderId, osId int64, osi *OrderReq.OrderSubItem,
	oneOrderData *OrderResp.OrderItem) error {
	for _, item := range oneOrderData.Goodss {
		if int(item.Options[0].Id) != osi.OptionId {
			continue
		}

		_, err := tx.Model("order_sub_activity").Unscoped().Insert(g.Map{
			"order_id":     orderId,
			"order_sub_id": osId,
			"activity_id":  item.ActivityId,
			"paid":         item.ActivityPaid,
			"discount":     item.ActivityDiscountMoney,
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// 处理 订单优惠券
func handleOrderSubCouponsByCreate(tx *gdb.TX, orderId, osId int64, osi *OrderReq.OrderSubItem,
	oneOrderData *OrderResp.OrderItem) error {

	// 找到现在对应的数据
	for _, item := range oneOrderData.OrderSubCoupons {
		if item.GoodsOptionId != osi.OptionId {
			continue
		}
		_, err := tx.Model("order_sub_coupon").Unscoped().Insert(g.Map{
			"order_id":         orderId,
			"order_sub_id":     osId,
			"member_coupon_id": oneOrderData.McId,
			"coupon_id":        item.CouponId,
			"discount":         item.Discount,
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// 处理 order_sub_coupon 相关
func handleOrderSubCoupons(tx *gdb.TX, orderId, osId int64, osi *OrderReq.OrderSubItem,
	oscs []OrderReq.OrderSubCoupon) error {
	for _, osc := range getOrderSubCoupons(osi, oscs) {
		_, err := tx.Model("order_sub_coupon").Unscoped().Insert(g.Map{
			"order_id":         orderId,
			"order_sub_id":     osId,
			"member_coupon_id": osc.MemberCouponId,
			"coupon_id":        osc.CouponId,
			"discount":         osc.Discount,
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// 获取 order_sub_coupon 所需要的数据
func getOrderSubCoupons(osi *OrderReq.OrderSubItem, oscs []OrderReq.OrderSubCoupon,
) []OrderReq.OrderSubCoupon {
	var fanhui []OrderReq.OrderSubCoupon
	for _, item := range oscs {
		if item.Hash != osi.Hash {
			continue
		}
		fanhui = append(fanhui, item)
	}

	return fanhui
}

// 统计子订单 paid 应付，discount 优惠金额
func getOrderSubPaidOrDiscount(typeStr string, osi *OrderReq.OrderSubItem,
	oscs []OrderReq.OrderSubCoupon) int64 {
	// 如果 oscs 为空时，说明没有优惠，金额则是原金额
	if len(oscs) < 1 {
		if typeStr == "paid" {
			// 实付
			return osi.TotalPrice
		} else {
			// 优惠
			return 0
		}
	}

	var jieguo int64 = 0
	for _, item := range oscs {
		if item.Hash != osi.Hash {
			continue
		}
		if typeStr == "paid" {
			jieguo += item.Paid
		} else {
			jieguo += item.Discount
		}
	}
	return jieguo
}

// 扣减用户的优惠券
func memberUseCouponByMemberCouponIds(tx *gdb.TX, memberCouponIds []int) error {
	update, err := tx.Model("member_coupon").Unscoped().Where(
		"delete_at < 1 AND id = (?) AND use_time < 1 AND (expires_time = 0 OR expires_time >= ?)",
		memberCouponIds, time.Now().Unix()).Update(g.Map{
		"use_time": time.Now().Unix(),
	})
	if err != nil {
		return err
	}
	affected, err := update.RowsAffected()
	if err != nil {
		return err
	}
	if int(affected) != len(memberCouponIds) {
		return errors.New("优惠券使用失败")
	}

	return nil
}

// 扣减商品库存
func reduceGoodsStock(tx *gdb.TX, ops []*OrderReq.ReduceGoodsStockUpdate) error {
	// 更新商品
	goodsIds := garray.NewIntArray(true)
	for _, item := range ops {
		update, err := tx.Model("goods_option").Unscoped().Where(
			"stock >= ? AND id = ?",
			item.ReduceStockNum, item.GoodsOptionId).Update(g.Map{
			"stock": gdb.Raw("stock-" + gconv.String(item.ReduceStockNum)),
		})
		if err != nil {
			return err
		}
		affected, err := update.RowsAffected()
		if err != nil {
			return err
		}

		if affected < 1 {
			return errors.New("扣减库存失败")
		}
		if !goodsIds.Contains(item.GoodsId) {
			goodsIds.Append(item.GoodsId)
		}

		// 加销量
		_, err = tx.Model("goods").Unscoped().Where("id", item.GoodsId).Update(g.Map{
			"sales": gdb.Raw("sales+" + gconv.String(item.ReduceStockNum)),
		})
		if err != nil {
			return err
		}
	}
	for _, goodsId := range goodsIds.Slice() {
		// 更新总库存
		err := goodsChangeRelated(tx, "stock", goodsId)
		if err != nil {
			return err
		}
		// 更新最小价格和最大价格
		/*err = goodsChangeRelated(tx, "price", goodsId)
		if err != nil {
			return err
		}*/
	}

	return nil
}

func goodsChangeRelated(tx *gdb.TX, typeStr string, goodsId int) error {
	dbPrefix := g.Cfg().GetString("database.prefix")
	if typeStr == "stock" {
		sql := "UPDATE " + dbPrefix + "goods g SET `stock` = "
		sql += "(SELECT IFNULL(SUM(go.stock),0) FROM " + dbPrefix + "goods_option go WHERE"
		sql += " go.delete_at < 1 AND go.is_open = 1 AND go.goods_id = g.id ) WHERE `id` = ?"
		// 更新总库存
		_, err := tx.Exec(sql, goodsId)
		if err != nil {
			return err
		}
	}
	if typeStr == "price" {
		// 更新最小价格和最大价格
		sql := "UPDATE " + dbPrefix + "goods g SET "
		sql += "`min_price` = (SELECT IFNULL(MIN(go.sell_price),0) FROM " + dbPrefix + "goods_option go WHERE go.delete_at < 1 AND go.is_open = 1 AND go.goods_id = g.id )"
		sql += ","
		sql += "`max_price` = (SELECT IFNULL(MAX(go.sell_price),0) FROM " + dbPrefix + "goods_option go WHERE go.delete_at < 1 AND go.is_open = 1 AND go.goods_id = g.id )"
		sql += " WHERE `id` = ?"

		_, err := tx.Exec(sql, goodsId)
		if err != nil {
			return err
		}
	}

	return nil
}
